import React, { useEffect, useState } from 'react'
import { Tag } from 'antd';
import { useSelector } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import menuData from '@/config';
import { addTag, removeTag } from '@/store/redux/table';
import { useDispatch } from 'react-redux';
import { CloseOutlined } from '@ant-design/icons';
const Tags = () => {
    const location = useLocation();
    const dispatch = useDispatch()
    const navigate = useNavigate();
    const tagsList = useSelector((state: any) => state.tab.tagsList);
    const [index, setIndex] = useState(null)
    const handleTag = (tag) => {
        navigate(tag.path);
    }
    const handleColse = (tag, idx) => {
        setIndex(idx)
        dispatch(removeTag({ path: tag.path }))
    }
    useEffect(() => {
        let tabObj
        menuData.forEach((item: any) => {
            if (location.pathname.indexOf(item.path) !== -1) {
                tabObj = item
                if (tabObj.children) {
                    const matchedChild = item.children.find((child: any) => child.path === location.pathname);
                    if (matchedChild) tabObj = matchedChild
                }
            }
        })
        if (tabObj) {
            dispatch(addTag(tabObj));
        }
    }, [dispatch, location.pathname])
    useEffect(() => {
        if (index === null) return;
        navigate(tagsList[index]?.path || '/home');
    }, [tagsList, navigate, index])
    return (
        <div style={{ margin: '5px' }}>
            {tagsList.map((item: any, idx: number) => {
                return <Tag style={{ padding: '10px' }} closeIcon={idx !== 0 ? <CloseOutlined /> : null} key={item.path} color={item.path === location.pathname ? '#6495ED' : '#AAA'} onClick={() => handleTag(item)} onClose={() => { handleColse(item, idx) }}>
                    {item.label}
                </Tag>
            })}

        </div>
    )
}

export default Tags